﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;

namespace TL_Cloud.Common
{
    /// <summary>
    /// 短息发送
    /// </summary>
    public class SmsSender : ISmsSender
    {
        private SmsConfig _smsConfig;
        private ILoggerFactory loggerFactory;
        public SmsSender(IOptions<SmsConfig> option_sms, ILoggerFactory loggerFactory)
        {
            _smsConfig = option_sms.Value;
            this.loggerFactory = loggerFactory;
        }
        /// <summary>
        /// 发送短息
        /// </summary>
        /// <param name="number">电话号码</param>
        /// <param name="message">短信内容</param>
        /// <param name="dictsURLExtends">短信请求地址后面追加的url的扩展字典</param>
        public Tuple<bool, string> Sender(string number, string message, bool isNotice)
        {
            return Task.Run<Tuple<bool, string>>(() =>
            {
                try
                {
                    Dictionary<string, string> dictUrl = new Dictionary<string, string>();
                    if(isNotice)
                    {
                        dictUrl.Add("productid", "887362");
                    }
                    else
                    {
                        dictUrl.Add("productid", "676767");
                    }
                    TL_Cloud.Utils.SmsHelper smsHelper = new Utils.SmsHelper(_smsConfig.SMSUrl, _smsConfig.SMSAccount, _smsConfig.SMSPwd, _smsConfig.SMSSign);
                    string msg = smsHelper.SendSms(number, message, dictUrl);
                    if (string.IsNullOrEmpty(msg))
                    {
                        return new Tuple<bool, string>(true, "");
                    }
                    else
                    {
                        return new Tuple<bool, string>(false, msg);
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    Trace.WriteLine($"{typeof(SmsSender)}出现异常；异常信息为:" + ex.Message);
#endif
                    if (loggerFactory != null)
                    {
                        var logger = loggerFactory.CreateLogger<SmsSender>();
                        logger.LogError($"{typeof(SmsSender)}出现异常;异常信息为:" + ex.Message + System.Environment.NewLine
                            + $"操作数据：短信内容:{number} 接收者:{number}");
                    }
                    return new Tuple<bool, string>(false, ex.Message);

                }
            }).Result;
        }
    }
}
